package com.example.videoweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.videoweb.domain.Barrage;
import com.example.videoweb.domain.Video;
import com.example.videoweb.service.ConsumerService;
import com.example.videoweb.service.StatisticalService;
import com.example.videoweb.service.VideoService;
import com.example.videoweb.utils.methods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;


@RestController
@RequestMapping("/video")
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private StatisticalService statisticalService;

    //添加视频
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object addVideo(@RequestParam("file") MultipartFile file[],
                           @RequestParam("authorId") String authorId,
                           @RequestParam("videoName") String videoName,
                           @RequestParam("duration") String duration,
                           @RequestParam("style") String style1,
                           @RequestParam("introduction") String introduction){

        Byte style = methods.changeStyle(style1);
        JSONObject jsonObject = new JSONObject();

        if(file[0].isEmpty()||file[1].isEmpty()){
            jsonObject.put("code",0);
            jsonObject.put("msg","文件上传失败");
            return jsonObject;
        }


        if(videoName == null||videoName.equals("")){
            jsonObject.put("code",0);
            jsonObject.put("msg","视频名不能为空");
            return jsonObject;
        }

        //文件名=当前时间的毫秒+原来的文件名
        String fileName1 = System.currentTimeMillis()+file[0].getOriginalFilename();  //视频
        String fileName2 = System.currentTimeMillis()+file[1].getOriginalFilename();  //封面
        //文件路径
        String filePath1 = System.getProperty("user.dir")+System.getProperty("file.separator")+"video";
        String filePath2 = System.getProperty("user.dir")+System.getProperty("file.separator")+"videoPic";
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath1);
        File file2 = new File(filePath2);
        if(!file1.exists()){
            file1.mkdir();
        }
        if(!file2.exists()){
            file2.mkdir();
        }

        //实际的文件地址
        File dest1 = new File(filePath1+System.getProperty("file.separator")+fileName1);
        File dest2 = new File(filePath2+System.getProperty("file.separator")+fileName2);
        //存储到数据库里的相对文件地址
        String storeVideoPicPath = "/video/"+fileName1;
        String storeVideoPath = "/videoPic/"+fileName2;
        //作者名
        String authorName = consumerService.selectByPrimaryKey(Integer.parseInt(authorId)).getUsername();
        try {
            file[0].transferTo(dest1);
            file[1].transferTo(dest2);

            Video video = new Video();
            video.setAuthorId(Integer.parseInt(authorId));
            video.setAuthorName(authorName);
            video.setVideoName(videoName);
            video.setDuration(Integer.parseInt(duration));
            video.setStyle(new Byte(style));
            video.setIntroduction(introduction);
            video.setPic(storeVideoPath);
            video.setUrl(storeVideoPicPath);
            video.setPraise(0);
            video.setPlayNumber(0);

            boolean flag = videoService.insert(video);
            if (flag) {
                statisticalService.numUp("style"+style);
                jsonObject.put("code",1);
                jsonObject.put("msg","上传成功");
                return jsonObject;
            }
            jsonObject.put("code",0);
            jsonObject.put("msg","上传失败");
            return jsonObject;
        } catch (IOException e) {
            jsonObject.put("code",0);
            jsonObject.put("msg","上传失败"+e.getMessage());
        }finally {
            return jsonObject;
        }
    }

    //修改视频信息
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object updateVideo(@RequestParam("file") MultipartFile file[],
                              @RequestParam("id") Integer id,
                              @RequestParam("authorId") String authorId,
                              @RequestParam("videoName") String videoName,
                              @RequestParam("duration") String duration,
                              @RequestParam("style") String style1,
                              @RequestParam("introduction") String introduction) {
        Byte style = methods.changeStyle(style1);
        JSONObject jsonObject = new JSONObject();

        if(videoName == null||videoName.equals("")){
            jsonObject.put("code",0);
            jsonObject.put("msg","视频名不能为空");
            return jsonObject;
        }

        Video video = new Video();

        if(!file[0].isEmpty()){//视频
            //删除原视频
            String url = videoService.selectByPrimaryKey(id).getUrl();
            File file0=new File(System.getProperty("user.dir")+"/"+url);
            if(file0.exists() && file0.isFile()){
                file0.delete();
            }

            String fileName1 = System.currentTimeMillis()+file[0].getOriginalFilename();
            String filePath1 = System.getProperty("user.dir")+System.getProperty("file.separator")+"video";
            File file1 = new File(filePath1);
            if(!file1.exists()){
                file1.mkdir();
            }
            File dest1 = new File(filePath1+System.getProperty("file.separator")+fileName1);
            String storeVideoPath = "/video/"+fileName1;
            try {
                file[0].transferTo(dest1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            video.setUrl(storeVideoPath);
            video.setDuration(Integer.parseInt(duration));
        }
        if(!file[1].isEmpty()){//封面
            //删除原封面
            String pic = videoService.selectByPrimaryKey(id).getPic();
            File file0=new File(System.getProperty("user.dir")+"/"+pic);
            if(file0.exists() && file0.isFile()){
                file0.delete();
            }

            String fileName2 = System.currentTimeMillis()+file[1].getOriginalFilename();
            String filePath2 = System.getProperty("user.dir")+System.getProperty("file.separator")+"videoPic";
            File file2 = new File(filePath2);
            if(!file2.exists()){
                file2.mkdir();
            }
            File dest2 = new File(filePath2+System.getProperty("file.separator")+fileName2);
            String storeVideoPicPath = "/videoPic/"+fileName2;
            try {
                file[0].transferTo(dest2);
            } catch (IOException e) {
                e.printStackTrace();
            }
            video.setPic(storeVideoPicPath);
        }

        //作者名
        String authorName = consumerService.selectByPrimaryKey(Integer.parseInt(authorId)).getUsername();

        video.setId(id);
        video.setAuthorId(Integer.parseInt(authorId));
        video.setAuthorName(authorName);
        video.setVideoName(videoName);
        video.setStyle(new Byte(style));
        video.setIntroduction(introduction);

        boolean flag = videoService.update(video);
        if (flag) {
            jsonObject.put("code",1);
            jsonObject.put("msg","上传成功");
            return jsonObject;
        }
        jsonObject.put("code",0);
        jsonObject.put("msg","上传失败");
        return jsonObject;
    }

    //删除视频
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public Object deleteVideo(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        boolean flag = videoService.delete(Integer.parseInt(id));
        if (flag){
            Byte style = videoService.selectByPrimaryKey(Integer.parseInt(id)).getStyle();
            statisticalService.numDown("style"+style);
        }
        return flag;
    }

    //根据id查询视频
    @RequestMapping(value = "/getById",method = RequestMethod.GET)
    public Object getById(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        return videoService.selectByPrimaryKey(Integer.parseInt(id));
    }

    //根据id增加播放量
    @RequestMapping(value = "/playNumUp",method = RequestMethod.GET)
    public Object playNumUp(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        return videoService.playById(Integer.parseInt(id));
    }

    //根据id增加点赞数
    @RequestMapping(value = "/praiseUp",method = RequestMethod.GET)
    public Object praiseUp(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        return videoService.praiseUp(Integer.parseInt(id));
    }

    //根据id减少点赞数
    @RequestMapping(value = "/praiseDown",method = RequestMethod.GET)
    public Object praiseDown(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        return videoService.praiseDown(Integer.parseInt(id));
    }

    //根据风格查询视频
    @RequestMapping(value = "/getByStyle",method = RequestMethod.GET)
    public Object getByStyle(HttpServletRequest request){
        String style = request.getParameter("style").trim();
        return videoService.getByVideoStyle(Byte.parseByte(style));
    }

    //根据风格查询视频
    @RequestMapping(value = "/getByStyle2",method = RequestMethod.GET)
    public Object getByStyle2(HttpServletRequest request){
        String style = request.getParameter("style").trim();
        return videoService.getByVideoStyle2(Byte.parseByte(style));
    }

    //根据关键字模糊查询视频
    @RequestMapping(value = "/getByVideoName",method = RequestMethod.GET)
    public Object getByVideoName(HttpServletRequest request){
        String videoName = request.getParameter("videoName").trim();
        return videoService.getByVideoName(videoName);
    }

    //查询所有前端视频
    @RequestMapping(value = "/allVideo",method = RequestMethod.GET)
    public Object allVideo(HttpServletRequest request){
        return videoService.allVideo();
    }

    //根据作者id查询视频
    @RequestMapping(value = "/getByAuthorId",method = RequestMethod.GET)
    public Object getByAuthorId(HttpServletRequest request){
        String authorId = request.getParameter("authorId").trim();
        return videoService.getByAuthorId(Integer.parseInt(authorId));
    }

    //增弹幕
    @RequestMapping(value = "/addBarrage",method = RequestMethod.POST)
    public void addBarrage(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        String consumerId = request.getParameter("consumerId").trim();
        String time = request.getParameter("time").trim();
        String content = request.getParameter("content").trim();

        //获取原弹幕
        Video video1 = videoService.selectByPrimaryKey(Integer.parseInt(id));
        String barrage = video1.getBarrage();
        String newBarrage = "";
        Video video = new Video();
        video.setId(Integer.parseInt(id));
        if (barrage != null && !"".equals(barrage)){
            int i;
            boolean flag = false;
            String arr[] =barrage.split("\n") ;
            //弹幕是否大于1000条
            boolean TooMore = arr.length > 999?true:false;
            for (i = 0;i < arr.length;i++){
                if (flag == false && Float.parseFloat(arr[i].substring(1,arr[i].indexOf("]")))-Float.parseFloat(time) > 0){
                    newBarrage = newBarrage + "["+time+"]" + consumerId + content+"\n";
                    flag = true;
                    if (!TooMore){
                        i--;
                    }
                } else if(i != 999){
                    newBarrage = newBarrage + arr[i] +"\n";
                }
            }
            if(flag == false){
                newBarrage = newBarrage + "["+time+"]" + consumerId+ content+"\n";
            }
            video.setBarrage(newBarrage);
        }else{
            video.setBarrage("["+time+"]" + consumerId + content+"\n");
        }
        videoService.update(video);
    }

    //根据id获取弹幕
    @RequestMapping(value = "/getBarrageById",method = RequestMethod.GET)
    public Object getBarrageById(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        String oriBarrage = videoService.getByBarrage(Integer.parseInt(id));
        if (oriBarrage != null){
            String barrage[] = oriBarrage.split("\n");
            Barrage barrage1[] = new Barrage[barrage.length];
            for (int i = 0; i < barrage.length; i++){
                Barrage barrage2 = new Barrage();
                barrage2.setTime(barrage[i].substring(1,barrage[i].indexOf("]")));
                barrage2.setConsumerId(barrage[i].substring(barrage[i].indexOf("]") + 1, barrage[i].indexOf(":")));
                barrage2.setContent(barrage[i].substring(barrage[i].indexOf(":") + 1));
                barrage1[i] = barrage2;
            }
            return barrage1;
        }
        return null;
    }

    //根据详细信息删除弹幕
    @RequestMapping(value = "/delBarrage",method = RequestMethod.POST)
    public void delBarrage(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        String delBarrage = request.getParameter("delBarrage").trim();
        Video video = new Video();
        String oldBarrage = videoService.getByBarrage(Integer.parseInt(id));

        video.setId(Integer.parseInt(id));
        video.setBarrage(oldBarrage.substring(0,oldBarrage.indexOf(delBarrage+"\n"))+oldBarrage.substring(oldBarrage.indexOf(delBarrage+"\n")+delBarrage.length()+1));
        videoService.update(video);
    }

    //获取风格数量
    @RequestMapping(value = "/selectByStyle",method = RequestMethod.GET)
    public Object selectByStyle(HttpServletRequest request){
        return statisticalService.selectByStyle();
    }
}


